package kz.edu.sdu.atm.db;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import kz.edu.sdu.atm.models.UserDTO;
import kz.edu.sdu.atm.models.UserFDTO;
import kz.edu.sdu.atm.util.Logger;

public class FileDbAdapter implements IGenericDbAdapter {
	Logger log = new Logger(FileDbAdapter.class);
	File storagFile;
	Map<String, UserDTO> userMap = new HashMap<String, UserDTO>();

	public FileDbAdapter(File file){
		storagFile = file;
		init();
	}

	public void init(){
		if (!storagFile.exists()){
			log.error(String.format("file does not exist: %s", storagFile
					.getAbsolutePath()));
			return;
		}
		try{
			userMap.clear();
			BufferedReader in = new BufferedReader(new FileReader(storagFile));
			while (in.ready()){
				String line = in.readLine();
				if (line != null && line.length() > 0){
					UserFDTO tmp = new UserFDTO();
					if (tmp.init(line)){
						userMap.put(tmp.getUsername(), tmp);
					}
				}
			}
			in.close();
		}catch(IOException e){
			e.printStackTrace();
		}
	}

	public void flush(){
		try{
			PrintWriter out = new PrintWriter(new  FileWriter(storagFile));
			for (UserDTO e : userMap.values()){
				UserFDTO ef = (UserFDTO) e;
				ef.save(out);
			}
			out.close();
		}catch(IOException e){
			log.error(e.toString());
		}catch(Exception e){
			log.error(e.toString());
		}
	}

	@Override
	public UserDTO getUser(String username) {
		return userMap.get(username);
	}

	@Override
	public void saveUser(UserDTO user) {
		if (user instanceof UserFDTO){
			if (userMap.containsKey(user.getUsername())) {
				userMap.remove(user.getUsername());
			}
			userMap.put(user.getUsername(), user);
		} else {
			UserFDTO nu = new UserFDTO(user);
			if (userMap.containsKey(nu.getUsername())) {
				userMap.remove(nu.getUsername());
			}
			userMap.put(nu.getUsername(), nu);
		}
	}

	@Override
	public void destroy() {
		flush();
	}


}
